import {
  Component,
  ComponentFactoryResolver,
  ComponentRef,
  HostListener,
  OnDestroy,
  OnInit,
  ViewChild,
  ViewContainerRef
} from "@angular/core";
import {dynacomponentMap} from "../sjgzxin.zs/sjgz-basecode";
import {CommService} from "../comm-service";
import {CompMap} from "../dynacomponent/dynamaner.component";
import {SharedService} from "../shared-service";
import {MyhttpService} from "../myhttp.service";
import {LocalStorageService} from "../local-storage-service";
import {Router} from "@angular/router";

declare var $: any;
declare var AMap: any;

@Component({
  template: `
    <div class="Room" [style.height]="RoomHeightstr">
      <div class="kdbms_room">
        <div class="ncdiv">
          <ng-container #kdbmsRoom>
            <div class="mapctr">
              <div class="lroom fl">
                <div class="icon_item" *ngFor="let item of markericonList">
                  <span class="item_img"><img [src]="item.icon"/></span>
                  <span>{{item.mc}}:&nbsp;&nbsp;{{item.sl}}</span>
                </div>
              </div>
              <div class="rroom fr">
                <div class="ctritem">
                  <select class="" id="ssgjRefreshpl" (change)="ssgjRefreshTime()">
                    <option value="10000">10s</option>
                    <option value="20000">20s</option>
                    <option value="30000">30s</option>
                  </select>
                </div>
                <div class="ctritem">
                  <div class="mybtn" (click)="getcheckedbqssgj()">
                    <i class="fa fa-refresh"></i>&nbsp;&nbsp; 刷新
                  </div>
                </div>
              </div>
            </div>
            <div id="mapdiv" class="mapdiv"></div>
          </ng-container>
        </div>
      </div>
    </div>
  `,
  styles: [
    ".Room{overflow: auto}",
    ".kdbms_room{width: 1920px;height: 1022px;overflow: hidden;background-color:#d9dcde;padding:5.5px 5px;}",
    ".ncdiv{width:1910px;height:1011px;position: relative;}",
    // 地图，固定部分
    ".mapctr{position: absolute;left: 482.5px;top: 5px; height: 35px;width: 1422.5px;background-color: #ffffff;z-index: 100;border-bottom: 3px solid #ccc}",
    ".mapctr>.lroom{height: 30px;width: auto}",
    ".mapctr>.rroom{height: 30px;width: auto}",
    ".lroom>.icon_item{display: inline-block;height: 30px;margin-left: 20px;}",
    ".lroom>.icon_item>.item_img{display: inline-block;width: 40px;height: 30px;padding: 5px 10px}",
    ".lroom>.icon_item>.item_img>img{width: 100%;height: 100%}",
    ".rroom>.ctritem{display: inline-block;height: 30px; margin-right: 15px;margin-top: 2.5px;}",
    ".rroom>.ctritem>.mybtn{width: auto;height: 30px;line-height: 30px;  padding: 0px 10px; border-radius: 15px;text-align: center; background-color: #0E97E6;color: #ffffff;cursor: pointer;}",
    ".mapdiv{ position: absolute;left: 477.5px;top: 0px;border:5px solid #ccc; width: 1432.5px;height:674px;}",
  ]
})
export class BmsjkdComponent implements OnInit, OnDestroy {
  RoomHeightstr: string = "0px";
  oneh: number = 0;
  onew: number = 0;
  map: any;
  geocoder: any; // 搜索服务插件
  graspobj: any; // 轨迹纠偏服务插件
  mapwin: any; // 信息窗口对象
  dynacomponentMapinit: any[] = [];
  main_pz_XY: any[] = [];
  markericonList: any[] = [{
    mc: "在线",
    sl: 0,
    icon: "assets/img/sjgz/zd_run.png"
  },
    //   {
    //   mc: "静止",
    //   sl: 16,
    //   icon: "assets/img/sjgz/zd_stop.png"
    // },
    {
      mc: "离线",
      sl: 0,
      icon: "assets/img/sjgz/zd_lx.png"
    }];
  lock_bmskdsjbtj: any;
  bmskdsjbtjInterval: number = 30000;
  checkedBmsKdList: any[] = [];
  bmskdtjmarker: any = {}; // key --bmsbh/kdbh  value --marker
  lock_ssgj: any;
  ssgjInterval: number = 10000;
  checkedbqids: any[] = [];
  checkedbqList: any[] = [];
  checkedPointerlist = {}; // // key--标签id  value--[],进入页面开始，获取到的实时数据点集合
  checkedMarker: any = {}; // key--标签id   value---object,标签marker对象
  checkedPolyline: any = {}; // key--标签id   value --object,标签路径对象
  checkedbqMsg: any = {}; // key --标签id   value--obj,标签对象
  checkedbq_clicklinstener: any = {}; // key --id  value:对应的marker的绑定事件对象

  activebqobj: any; // 标签列表中，高亮的标签
  activebq_lspointerArr: any[] = []; //存放高亮的终端，所有的历史轨迹点
  nowclickcar: any;  // 信息窗口

  timeRange: number = 600000; // ms (毫秒)  过时的判断依据
  carIcon: any = {
    "bq_xs": "assets/img/sjgz/car_blue.png",  // 行驶
    "bq_jz": "assets/img/sjgz/car_red.png",  // 静止
    "bq_lx": "assets/img/sjgz/car_gs.png",  // 离线
  };
  polylineColor: any = {
    "bq_xs": "#076CFE", // 行驶
    "bq_jz": "#F70808", //  静止
    "bq_lx": "#313030",  // 离线
  };


  //#########################实时跟踪 #########################
  /**
   * 实时轨迹，刷新频率的切换
   */
  ssgjRefreshTime(): void {
    if (this.lock_ssgj) {
      clearInterval(this.lock_ssgj);
    }
    this.ssgjInterval = $("#ssgjRefreshpl").val();
    this.getcheckedbqssgj();
    this.lock_ssgj = setInterval(() => {
      this.getcheckedbqssgj()
    }, this.ssgjInterval)
  }

  /**
   * 获取勾选的标签的，实时位置信息
   */
  getcheckedbqssgj(): void {
    if (!this.checkedbqids.length) {
      return
    }
    this.commService.log("请求实时轨迹的标签ids", this.checkedbqids);
    const cxxxListv = this.checkedbqids.map((id_n) => {
      const pointerarr = this.checkedPointerlist[id_n];
      return {
        id: id_n,
        lssj: pointerarr.length > 0 ? pointerarr[pointerarr.length - 1].sj : ""
      }
    });
    const url = "sjgz/gjcx/cxssgj";
    this.itservice.kwPtPost(url, {
      cxlx: "dzbqsb",
      cxxxList: cxxxListv
    }).subscribe(resp => {
      this.commService.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const allroadPointerList = resp.ssgjcxList ? resp.ssgjcxList : [];
            if (!allroadPointerList.length) {
              return
            }
            allroadPointerList.forEach((item) => {
              const id_n = item.id;  //标签id
              const ssgjlist_n = item.ssgjList ? item.ssgjList : []; // 标签 从 上个点时间到现在的实时坐标点集合
              // 标签的， 没有 sbbqidList
              this.showSsPosition(id_n, ssgjlist_n);
              ssgjlist_n.forEach((pointer) => {
                this.checkedPointerlist[id_n].push(pointer);  // 实时点数据前端记录
              });
            });
          }
        }
      });
    })
  }

  /**
   *
   * @param {string} id_n   标签 id
   * @param pointerArr    标签 实时返回数据列表
   */
  showSsPosition(id_n: string, pointerArr: any): void {
    const that = this;
    let lastpointer_n: any; //id 实时最后一个坐标点
    if (pointerArr.length) {
      lastpointer_n = pointerArr[pointerArr.length - 1];
    } else {
      const cachePointerList_n = this.checkedPointerlist[id_n];
      if (cachePointerList_n.length) {
        lastpointer_n = cachePointerList_n[cachePointerList_n.length - 1];
      } else {
        lastpointer_n = null;
      }
    }
    //id_n 实时轨迹，自始至终都没有一个点，图标 轨迹均不做处理
    if (!lastpointer_n) {
      if (this.activebqobj) {
        const activezdid = this.activebqobj.id;
        if (activezdid == id_n) {
          that.sharedService.emitChange({
            actiontype: "toggleActiveBq",
            data: {
              activebqobj: that.activebqobj,
            }
          });
        }
      }
      return
    }
    if (!lastpointer_n.jd || !lastpointer_n.wd) {
      // 处理后端返回的错误数据
      return
    }
    this.commService.warn("轨迹最后一个点所属id_n", id_n, lastpointer_n);
    const sj_n = lastpointer_n.sj; // 时间
    const sd_n = lastpointer_n.sd; //速度
    const fxj_n = lastpointer_n.fxj; //方向角
    const jd_n = lastpointer_n.jd; //经度
    const wd_n = lastpointer_n.wd; // 维度
    const dl_n = lastpointer_n.dl; //终端电量
    const gnssdl_n = lastpointer_n.gnssdl;// gnss电量
    const lydl_n = lastpointer_n.lydl; // 蓝牙电量
    const flag = this.getTimerange(lastpointer_n.sj);  // true--离线   false-非离线
    let marker_iconurl: string = ""; //勾选的终端marker 图标
    let line_color: string = ""; //  高亮的终端线颜色 【只有高亮的终端会显示轨迹线（先颜色和图标颜色一致），其他的勾选终端是显示实时位置】
    if (flag) {
      marker_iconurl = this.carIcon["bq_lx"];
      line_color = this.polylineColor["bq_lx"];
    } else {
      if (Number(sd_n) > 0) {
        marker_iconurl = this.carIcon["bq_xs"];
        line_color = this.polylineColor["bq_xs"];
      } else {
        marker_iconurl = this.carIcon["bq_jz"];
        line_color = this.polylineColor["bq_jz"];
      }
    }
    //##########   生成 marker对象
    const markobj: any = {}; // id  实时车辆信息对象
    markobj["id_n"] = id_n;//
    markobj["fxj"] = fxj_n;
    markobj["sd"] = sd_n;//mqtt中信息中，车速 km/h
    markobj["sj"] = sj_n; // 时间
    markobj["dl"] = dl_n; // 终端电量
    markobj["gnssdl"] = gnssdl_n; // gnssdl电量
    markobj["lydl"] = lydl_n; // lydl 电量
    markobj["position"] = [jd_n, wd_n];
    markobj["zxzt"] = flag ? "1" : "0"; // 0 --在线   1--离线
    markobj["zxztmc"] = flag ? "离线" : "在线";
    const bqmsg_n = this.checkedbqMsg[id_n];
    markobj["sjbmc"] = bqmsg_n.text; // 试卷包名称
    const id_n_marker = this.checkedMarker[id_n];
    if (!id_n_marker) {
      this.checkedMarker[id_n] = new AMap.Marker({
        map: that.map,
        //position: markobj.position,
        offset: new AMap.Pixel(-17, -9),
        //angle: Number(markobj.fxj) + 90 + 180,
        icon: new AMap.Icon({
          //34x18px
          image: marker_iconurl,
          imageOffset: new AMap.Pixel(0, 0),
          imageSize: new AMap.Size(34, 18)
        }),
        zIndex: 100,  //默认值是100
        extData: markobj
      });
    }
    this.checkedMarker[id_n].setIcon(new AMap.Icon({
      image: marker_iconurl,
      imageOffset: new AMap.Pixel(0, 0),
      imageSize: new AMap.Size(34, 18)
    }));
    this.checkedMarker[id_n].setPosition(markobj.position);
    this.checkedMarker[id_n].setAngle(Number(markobj.fxj) + 90 + 180); //  0 = 车marker正东方向（顺时针，可以大于360），终端 fxj= 与正北方向顺时针夹角
    this.checkedMarker[id_n].setExtData(markobj);

    // ###########   生成轨迹线对象， 后续高亮的终端【只有高亮的终端会显示轨迹线，线的颜色和图标颜色一致】要使用到
    const id_n_Polyline = this.checkedPolyline[id_n];
    if (!id_n_Polyline) {
      this.checkedPolyline[id_n] = new AMap.Polyline({
        map: this.map,
        strokeColor: line_color,
        strokeOpacity: 1,
        strokeWeight: 5,
        strokeStyle: "solid",
        strokeDasharray: [10, 5],
        zIndex: 50,  //默认值是 50
      });
    }
    this.checkedPolyline[id_n].setOptions({
      strokeColor: line_color
    });
    if (this.activebqobj) {
      const activezdid = this.activebqobj.id;
      if (activezdid == id_n) {
        this.getactiveHistoryPointer();
        let pointerlist_n = pointerArr.slice();
        if (this.activebq_lspointerArr.length) {
          // concat的原因是， 怕  activezd_lspointerArr 获取的接口太迟缓，会出现断点
          pointerlist_n = this.activebq_lspointerArr.concat(this.checkedPointerlist[id_n] ? this.checkedPointerlist[id_n] : []).concat(pointerlist_n);
        }
        let linedata = pointerlist_n.map(function (value) {
          return [value.jd, value.wd];
        });
        this.checkedPolyline[id_n].setPath(linedata);
        //高亮的终端要自动弹出信息窗口
        that.updataWindowMessase(markobj, (resp) => {
          this.mapwin.setContent(resp);
        });//更新信息窗口内容，这个 that.nowclickcar不是即时的
        this.mapwin.open(this.map, markobj.position); //显示信息窗口
        that.nowclickcar = markobj;
        that.nowclickcar["isshow"] = true;
        that.sharedService.emitChange({
          actiontype: "toggleActiveBq",
          data: {
            activebqobj: that.activebqobj,
          }
        });
      }
    }
    //############ 信息窗口处理 1： activezd 要显示信息窗口信息  2 ：点击的marker会变成activezd
    //防止重复绑定
    if (this.checkedbq_clicklinstener[id_n]) {
      AMap.event.removeListener(this.checkedbq_clicklinstener[id_n]);//移除事件，以绑定时返回的对象作为参数
    }
    this.checkedbq_clicklinstener[id_n] = AMap.event.addListener(this.checkedMarker[id_n], "click", function (e) {
      that.updataWindowMessase(markobj, (resp) => {
        that.mapwin.setContent(resp);
      });//获取新的窗口内容，这个item是即时的

      that.mapwin.open(that.map, markobj.position); //在地图上 显示信息窗口
      that.nowclickcar = markobj;
      that.nowclickcar["isshow"] = true;
      // that.mapwin.on('close', function () {
      //   that.nowclickcar["isshow"] = false;
      // });
      const arr = that.checkedbqList.filter((zdobj) => {
        return zdobj.id == markobj.id_n;
      });
      if (arr.length) {
        that.activebqobj = arr[0]
      } else {
        that.activebqobj = null;
      }
      that.getactiveHistoryPointer();
      that.sharedService.emitChange({
        actiontype: "toggleActiveBq",
        data: {
          activebqobj: that.activebqobj
        }
      })
    });
    const windowcloseflag = this.mapwin.getIsOpen();
    if (windowcloseflag) {
      that.nowclickcar["isshow"] = true;
    }
    if (this.nowclickcar && this.nowclickcar["id_n"] == id_n) {
      if (this.nowclickcar["isshow"]) {
        that.updataWindowMessase(markobj, (resp) => {
          this.mapwin.setContent(resp);
        });//更新信息窗口内容，这个 that.nowclickcar不是即时的
        this.mapwin.open(this.map, markobj.position); //显示信息窗口
      }
    }
  }


  /**
   * 某个实时轨迹点和 客户端时间差值,是否超过特定时间
   * @param {string} sj
   * @returns {boolean}
   */
  getTimerange(sj: string): boolean {
    const now = this.commService.convertTimeToInt(this.commService.YMDHMS_get(false));
    const lastsj = this.commService.convertTimeToInt(sj);
    this.commService.warn("时间差", "", (now - lastsj));

    this.commService.log("现在的电脑时间", this.commService.YMDHMS_get(false));
    this.commService.log("最后一条数据返回的时间", sj);
    return (now - lastsj) > this.timeRange;
  }

  updataWindowMessase(markobj: any, callback: Function): any {
    const markerlx = markobj.markerlx;
    const markerpostion = markobj.position;
    this.getAddresss(markerpostion, (resp) => {
      markobj["dzmc"] = resp.regeocode.formattedAddress;
      const info: any[] = [];
      info.push("试卷包 : " + markobj.sjbmc);
      info.push("地址 : " + markobj.dzmc);
      info.push("<br/>");
      info.push("<a>实时轨迹</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:void(0)' id='" + markobj.id_n + "' class='lsgj'>历史轨迹</a>");
      this.activebqobj["sswz"] = markobj["dzmc"];
      callback(info.join("<br/>"), markobj["dzmc"]);
    });
  }

  getAddresss(lnglatXY: any, callback: Function): void {
    this.geocoder.getAddress(lnglatXY, function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        callback(result);
      }
    });
  }


  //############  保密室 /考点  实时的试卷包信息统计  ##########
  getbmskdsjbtj(): void {
    if (!this.checkedBmsKdList.length) {
      return
    }
    const reqobj = {
      ksjhbh: this.localStorageService.get("hksjh"),
      kdbmsbhList: []
    };
    reqobj.kdbmsbhList = this.checkedBmsKdList.map((bms_kd_obj) => {
      const lxv = bms_kd_obj.type; // bms / bzhkd
      const bhv = bms_kd_obj.id; //
      return {
        lx: lxv,
        bh: bhv
      }
    });
    const url = "sjgz/zsymbmsjkd/kdbmscfsjbtj";
    this.itservice.kwPtPost(url, reqobj).subscribe(resp => {
      this.commService.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const bmscssjbtjListv = resp.bmscssjbtjList ? resp.bmscssjbtjList : [];
            const kdcssjbtjListv = resp.kdcssjbtjList ? resp.kdcssjbtjList : [];
            if (bmscssjbtjListv.length) {
              bmscssjbtjListv.forEach((OBJ) => {
                const bmsbhv = OBJ.bmsbh;
                const bmsmcv = OBJ.bmsmc;
                const jdv = OBJ.jd;
                const wdv = OBJ.wd;
                const kdsjbslListv = OBJ.kdsjbslList ? OBJ.kdsjbslList : [];
                this.drawMarker([jdv, wdv], bmsbhv, bmsmcv, "bms", kdsjbslListv);
              });
            }
            if (kdcssjbtjListv.length) {
              kdcssjbtjListv.forEach((obj) => {
                const kdbhv = obj.kdbh;
                const kdmcv = obj.kdmc;
                const jdv = obj.jd;
                const wdv = obj.wd;
                const sjbslv = obj.sjbsl;
                this.drawMarker([jdv, wdv], kdbhv, kdmcv, "bzhkd", [{kdmc: kdmcv, sjbsl: sjbslv}]);
              });
            }
          }
        }
      });
    });
  }

  clearBqMarkers(): void {
    const allbqmarkers: any[] = [];
    for (let bqid in this.checkedMarker) {
      if (this.checkedMarker[bqid]) {
        allbqmarkers.push(this.checkedMarker[bqid]);
      }
    }
    this.map.remove(allbqmarkers);
  }

  /**
   *
   * @param positionv           位置
   * @param {string} jdid       保密室编号/考点编号
   * @param {string} jdmc       保密室名称/考点名称
   * @param {string} lx         bms/bzhkd
   * @param kdsjb           考点试卷包信息
   */
  drawMarker(positionv: any, jdid: string, jdmc: string, lx: string, kdsjblist: any): void {
    let iconstr = "";
    let listrs: string = "";
    if (lx == "bms") {
      iconstr = "assets/img/sjgz/marker_bms.png";
      kdsjblist.forEach((item) => {
        listrs += `<li style='padding: 5px 0px'>${item.kdmc}：${item.sjbsl}</li>`;
      });
    } else if (lx == "bzhkd") {
      iconstr = "assets/img/sjgz/marker_kd.png";
      listrs += `<li style='padding: 5px 0px'>试卷包数量：${kdsjblist[0].sjbsl}</li>`;
    }
    if (!this.bmskdtjmarker[jdid]) {
      this.bmskdtjmarker[jdid] = new AMap.Marker({
        map: this.map,
        position: positionv,
        offset: new AMap.Pixel(-20, -15),
        //angle: Number(markobj.fxj) + 90 + 180,
        icon: new AMap.Icon({
          //34x18px
          image: iconstr,
          imageOffset: new AMap.Pixel(0, 0),
          imageSize: new AMap.Size(40, 30)
        }),
        zIndex: 100,  //默认值是100
        // extData: markobj
      });
    }
    this.bmskdtjmarker[jdid].setLabel({
      offset: new AMap.Pixel(60, 10),  //设置文本标注偏移量
      content: "<div  style='position: relative;width: 200px;height: auto;padding: 10px 15px;padding-bottom: 5px'><div style='position: absolute;left: 20px;top: -20px;width: 20px;height: 15px; border-bottom: 15px solid #0D73F3;border-left: 20px solid transparent;border-right: 20px solid transparent;'></div>" +
      "<div style='width: 100%;height: 25px;line-height: 25px;padding-left: 10px; border-left: 5px solid #0D73F3;font-size: 15px'>" + jdmc + "</div>" +
      "<ul style='list-style: none;padding-left: 15px;font-size: 12px'>" +
      listrs +
      "</ul></div>", //设置文本标注内容
      direction: 'bottom' //设置文本标注方位
    });
  }

  //##############主面板信息 ###################

  /**
   * 获取要加载的动态组件和位置信息
   */
  getMainComp(): void {
    this.main_pz_XY = [
      [{
        compkey: 'bmskd_bmskdlb',
        topbl: 0,
        leftbl: 0
      }, {
        compkey: 'gdmap',
        topbl: 0,
        leftbl: 1,
      }], [{
        compkey: 'bmskd_bmssjxx',
        topbl: 1,
        leftbl: 0,
      }, {
        compkey: 'gdmap',
        topbl: 1,
        leftbl: 1
      }], [{
        compkey: 'bmskd_sjbxx',
        topbl: 2,
        leftbl: 0,
      }, {
        compkey: 'bmskd_bqsjbxx',
        topbl: 2,
        leftbl: 1,
      }]
    ];
    this.initMaincomp(); //加载动态组件
  }

  initMaincomp(): void {
    $(".kdbms_room .comp").each((index, item) => {
      this.kdbmsroom.remove(index);
    });
    const checkRoomEmpty = setInterval(() => {
      if ($(".kdbms_room .comp").length == 0) {
        clearInterval(checkRoomEmpty);
        this.main_pz_XY.forEach((row) => {
          row.forEach((cell) => {
            const compkey = cell.compkey;
            const topbl = Number(cell.topbl);
            const leftbl = Number(cell.leftbl);
            const maintop = topbl * this.oneh;
            const mainleft = leftbl * this.onew;
            if (compkey != "gdmap") {
              const dynacomponentF = this.cfr.resolveComponentFactory(CompMap[compkey]);
              let compexist: boolean = false;
              const dynacomp_class = compkey.toString().split("_")[1];
              $(".kdbms_room .comp").each(function (index, item) {
                if ($(item).hasClass(dynacomp_class)) {
                  compexist = true;
                }
              });
              if (!compexist) {
                const dynacompRef = this.kdbmsroom.createComponent(dynacomponentF) as ComponentRef<any>;
                dynacompRef.instance.o = {
                  frompage: "bmskd",
                  topv: maintop,
                  leftv: mainleft,
                  compkey: compkey,
                  compw: this.dynacomponentMapinit[compkey]["wbs"] * this.onew,
                  comph: this.dynacomponentMapinit[compkey]["hbs"] * this.oneh,
                  paramchangelx: "",
                  paramchangedata: null
                };
                dynacompRef.instance.outhander.subscribe(resp => {
                });
              }
            }
          });
        });
      }
    }, 100);
  }

  initMap(): void {
    const that = this;
    this.map = new AMap.Map("mapdiv", {
      resizeEnable: true, //是否监控地图容器尺寸变化，默认值为false
      zoom: 11, //地图显示的缩放级别，若center与level未赋值，地图初始化默认显示用户所在城市范围，没有center（中心点）和level ，所以这个暂时无效
    });
    AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.Geocoder', "AMap.GraspRoad"],
      function () {
        //缩放，平易等工具条
        // that.map.addControl(new AMap.ToolBar());
        //比例尺
        //that.map.addControl(new AMap.Scale());
        //鹰眼
        that.map.addControl(new AMap.OverView({
          isOpen: false
        }));
        that.geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all"
        });
        that.map.addControl(that.geocoder);
        // 轨迹纠偏
        that.graspobj = new AMap.GraspRoad();
      });
    //信息窗口
    const info = [];
    //info.push("<div><div><img style=\"float:left;\" src=\" http://webapi.amap.com/images/autonavi.png \"/></div> ");
    info.push("<div style='padding:0px 0px 0px 4px'><b>" + "--" + "</b>");
    info.push("</div>");
    this.mapwin = new AMap.InfoWindow({
      content: info.join("<br/>") //使用默认信息窗体框样式，显示信息内容
    });
    this.mapwin.on('close', function () {
      that.nowclickcar["isshow"] = false;
    });
  }


  @HostListener("click", ["$event.target"])
  onClick(btn) {
    //btn 就是 $event.target 是个dom
    const islsgjdom = $(btn).attr("class");
    if (islsgjdom == "lsgj") {
      const sbid = $(btn).attr("id");
      const gjhfObj = {
        id: sbid,  // 终端id
        sblx: "dzbqsb"
      };
      this.localStorageService.set("hfsbxx", JSON.stringify(gjhfObj));
      setTimeout(() => {
        this.router.navigate(["sjgzxin.zs", "gjhf"]);
      }, 500);
    }
  }

  constructor(private commService: CommService,
              private cfr: ComponentFactoryResolver,
              private itservice: MyhttpService,
              private router: Router,
              private localStorageService: LocalStorageService,
              private sharedService: SharedService) {
    this.sharedService.changeEmitted$.subscribe(resp => {
      const actiontypev = resp.actiontype;
      const datav = resp.data;
      switch (actiontypev) {
        case "activeNode": {
          // 清空地图覆盖物（实时标签marker + 保密室/考点试卷包统计marker）
          this.map.clearMap();// 清楚地图所有覆盖物，信息窗口不属于覆盖物
          this.mapwin.close(); // 信息窗口关闭

          const activebqobjv = datav.activebqobj;  // 高亮的标签   可能是 null
          const checked_bmskdlist = datav.bmskdlist; // 勾选的 保密室+ 考点 列表    可能是 []
          const checked_bqlist = datav.bqlist;  // 勾选的    标签列表    可能是 []

          this.activebqobj = activebqobjv;
          this.checkedBmsKdList = checked_bmskdlist;
          this.checkedbqList = checked_bqlist;
          this.checkedbqids = this.checkedbqList.map((bqobj) => {
            const bqid = bqobj.id;
            this.checkedPointerlist[bqid] = [];
            this.checkedMarker[bqid] = null;
            this.checkedPolyline[bqid] = null;
            this.checkedbqMsg[bqid] = bqobj;
            return bqobj.id;
          });
          this.getcheckedbqssgj();

          this.checkedBmsKdList.forEach((item) => {
            const bms_kd_id = item.id;
            this.bmskdtjmarker[bms_kd_id] = null;
          });
          this.getbmskdsjbtj();
        }
          break;
        case "bqzttj": {
          const bqlistv = datav.bqlist;
          let zxcount: number = 0;
          let lxcount: number = 0;
          bqlistv.forEach((bqobj) => {
            const zxzt = bqobj.zxzt;
            if (zxzt == "1") {
              lxcount++;
            } else {
              zxcount++;
            }
          });
          this.markericonList.forEach((item, index) => {
            if (index == 0) {
              //在线
              item.sl = zxcount;
            } else if (index == 1) {
              //离线
              item.sl = lxcount;
            }
          });
        }
          break;
      }
    });

  }

  getactiveHistoryPointer(): void {
    if (!this.activebqobj) {
      return
    }
    this.activebq_lspointerArr = [];
  }

  /**
   * 使用window 对象的事件
   * @param event
   */
  @HostListener("window:resize", ["$event"])
  onResize(event) {
    this.RoomHeightstr = this.commService.getViewPort().height + "px";
  }

  @ViewChild("kdbmsRoom", {read: ViewContainerRef}) kdbmsroom: ViewContainerRef;

  ngOnInit() {
    this.onew = 1910 / 4;  // 477.5
    this.oneh = 1011 / 3;  //337
    this.initMap();
    this.commService.getSysmsg2((resp) => {
      if (resp) {
        const sysBase = resp.sysBase;
        this.dynacomponentMapinit = dynacomponentMap[sysBase];
        this.getMainComp();  // 加载动态组件
      }
    });
    this.RoomHeightstr = `${this.commService.getViewPort().height}px`;
    //实时轨迹
    this.getcheckedbqssgj();
    this.lock_ssgj = setInterval(() => {
      this.getcheckedbqssgj()
    }, this.ssgjInterval)
    // 实时 保密室/考点统计的试卷包数量
    this.getbmskdsjbtj();
    this.lock_bmskdsjbtj = setInterval(() => {
      this.getbmskdsjbtj();
    }, this.bmskdsjbtjInterval)
  }

  ngOnDestroy() {
    if (this.lock_ssgj) {
      clearInterval(this.lock_ssgj);
    }
    if (this.lock_bmskdsjbtj) {
      clearInterval(this.lock_bmskdsjbtj);
    }
  }

}
